package com.ai.ly.goodsautocat.common;

import java.util.LinkedList;
import java.util.List;

import com.ai.ly.goodsautocat.util.JiebaAnalysisUtil;
import com.ai.ly.goodsautocat.util.WordFilterFactory;
import com.ai.ly.goodsautocat.vo.PredictSampleVO;
import com.ai.ly.goodsautocat.vo.TrainningSampleVO;
import com.huaban.analysis.jieba.SegToken;

public class SampleFactory {
    
    public static TrainningSampleVO buildTrainningSample(String gdsName,String catId,ISampleInfoBuilder sampleInfoBuilder) {
        TrainningSampleVO sample=null;
        
        //对商品名称，进行分词
        List<String> wordList=getWordListFromGdsName(gdsName);//该样本分词后的单词列表
        if (wordList==null||wordList.size()<=0) {
            //如果这个样本的单词全都被过滤了，就不考虑了吧
            return null;
        }
        
        //商品分类
        double y=sampleInfoBuilder.getYValue(catId);
        sample=new TrainningSampleVO(sampleInfoBuilder.getDictSize(),y);
        //遍历分词，设置样本的X值
        for (String word : wordList) {
            int wordIndexInDict=sampleInfoBuilder.getIndexOfWordInDict(word);
            if (wordIndexInDict<=0) {
                continue;
            }
            sample.addIndexCount(wordIndexInDict);//从1开始
        }
        if (!sample.isInDict()) {
            //如果样本的单词都不在字典中，就过滤掉
            return null;
        }
        sample.setGdsName(gdsName);
        return sample;
    }
    
    public static PredictSampleVO buildPredictSample(String gdsName,ISampleInfoBuilder sampleInfoBuilder) {
        PredictSampleVO sample=null;
        
        //对商品名称，进行分词
        List<String> wordList=getWordListFromGdsName(gdsName);//该样本分词后的单词列表
        if (wordList==null||wordList.size()<=0) {
            //如果这个样本的单词全都被过滤了，就不考虑了吧
            return null;
        }
        
        //商品分类
        sample=new PredictSampleVO(sampleInfoBuilder.getDictSize());
        //遍历分词，设置样本的X值
        for (String word : wordList) {
            int wordIndexInDict=sampleInfoBuilder.getIndexOfWordInDict(word);
            if (wordIndexInDict<=0) {
                continue;
            }
            sample.addIndexCount(wordIndexInDict);//从1开始
        }
        if (!sample.isInDict()) {
            //如果样本的单词都不在字典中，就过滤掉
            return null;
        }
        sample.setGdsName(gdsName);
        return sample;
    }
    
    private static List<String> getWordListFromGdsName(String gdsName){
        List<SegToken> wordTokenList = JiebaAnalysisUtil.processInSearchMode(gdsName);
        if (wordTokenList==null||wordTokenList.size()<=0) {
            return null;
        }
        List<String> wordList=new LinkedList<>();//该样本分词后的单词列表
        for (SegToken segToken : wordTokenList) {
            String word=segToken.word;
            if (WordFilterFactory.shouldFilterWord(word)) {
                //一些单词要过滤掉
                continue;
            }
            wordList.add(word);
        }
        return wordList;
    }
    

}
